package jmine.tec.sync.channel;

import java.io.IOException;
import java.util.ArrayList;
import java.util.Collection;
import java.util.List;

import jmine.tec.rpc.sync.DatabaseSynchronizationCommand;
import jmine.tec.sync.DataPushChannel;
import jmine.tec.utils.io.IOUtils;
import jmine.tec.utils.register.Receiver;

/**
 * Implementacao de {@link DataPushChannel} que envia os comandos para mais de um cliente
 * 
 * @author takeshi
 */
public class MultipleDataPushChannel implements DataPushChannel, Receiver<DataPushChannel> {

    private final List<DataPushChannel> channels = new ArrayList<DataPushChannel>();

    /**
     * {@inheritDoc}
     */
    public void pushCommands(DatabaseSynchronizationCommand[] cmds) throws IOException {
        byte[] serialized = IOUtils.serializeObject(cmds);
        this.pushCommandsAsBytes(serialized);
    }

    /**
     * {@inheritDoc}
     */
    public synchronized void register(Collection<? extends DataPushChannel> registers) {
        this.channels.addAll(registers);
    }

    /**
     * {@inheritDoc}
     */
    public void pushCommandsAsBytes(byte[] data) throws IOException {
        for (DataPushChannel channel : this.channels) {
            channel.pushCommandsAsBytes(data);
        }
    }

}
